package per.zzzfwd.query;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CompoundPredicate implements Predicate, Renderable {

    private PredicateConjunction predicateConjunction;
    private List<Expression> expressions = new ArrayList<>();

    public CompoundPredicate(PredicateConjunction predicateConjunction, Expression... expressions) {
        this.predicateConjunction = predicateConjunction;
        this.expressions.addAll(Arrays.asList(expressions));
    }

    public CompoundPredicate(PredicateConjunction predicateConjunction, List<Expression> expressions) {
        this.predicateConjunction = predicateConjunction;
        this.expressions.addAll(expressions);
    }

    public PredicateConjunction getPredicateConjunction() {
        return predicateConjunction;
    }

    public List<Expression> getExpressions() {
        return expressions;
    }

    @Override
    public String render() {
        StringBuilder builder = new StringBuilder();
        String conjunction = "";
        builder.append("(");
        for (Expression expression : expressions) {
            builder
                .append(conjunction)
                .append(((Renderable) expression).render());
            conjunction = predicateConjunction == PredicateConjunction.AND ? " AND " : " OR ";
        }
        builder.append(")");
        return builder.toString();
    }
}
